package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.entity.SysAdminUser;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.PageUtil;
import com.ruoyi.common.core.page.ResultEntity;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.dto.SysUserDTO;
import com.ruoyi.system.domain.dto.UserResetDTO;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 用户信息
 *
 * @author ruoyi
 */
@Api(tags = "(客户端) 用户管理")
@RestController
@RequestMapping("/client/user")
public class SysUserController {
    @Autowired
    private ISysUserService userService;

    @PostMapping("/add")
    @ApiOperation(value = "新增用户")
    public ResultEntity add(@Valid @RequestBody SysUserDTO params) {
        userService.add(params);
        return ResultEntity.createSuccess();
    }

    @PostMapping("/update")
    @ApiOperation(value = "用户修改")
    public ResultEntity update(@Valid @RequestBody SysUserDTO.SysUserUpdate params) {
        userService.updateUser(params);
        return ResultEntity.createSuccess();
    }

    @GetMapping("/list")
    @ApiOperation(value = "用户列表查询",response = SysUser.class)
    public ResultEntity list(SysUserDTO params){
        PageUtil.startPage(params);
        return ResultEntity.createSuccess(PageUtil.getPageList(userService.listPage(params)));
    }

    @PostMapping("/del/{id}")
    @ApiOperation(value = "用户删除")
    public ResultEntity delete(@PathVariable Long id){
        SysUser entity = new SysUser();
        entity.setId(id);
        entity.setDelFlag(1);
        userService.updateById(entity);
        return ResultEntity.createSuccess();
    }
    @PostMapping("/resert")
    @Log(title = "修改密码", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "修改密码",response = SysAdminUser.class)
    public ResultEntity add(@Validated @RequestBody UserResetDTO params){
        //检查用户原密码是否一致
        SysUser user = userService.getById(params.getId());
        if(!SecurityUtils.matchesPassword(params.getPassword(),user.getPassword())){
            throw new BaseException("原密码输入错误!");
        }
        user.setPassword(SecurityUtils.encryptPassword(params.getNewPassword()));
        userService.updateById(user);
        return ResultEntity.createSuccess();
    }

}
